<template>
  <div class="learn-bench-view">
    <div class="bench-main">
      <div class="resource-section">
        <!--视频播放-->
        <div class="v-r" v-if="currentContent.type === 0">
          <vue-aliplayer-v2
              @ready="handleReady"
              @play="handlePlay"
              @pause="handlePause"
              @completeSeek="handleCompleteSeek"
              ref="VueAliplayerV2"
              @timeupdate="handleTimeupdate"
              :options="options"
          />
        </div>
        <!--文档播放-->
        <div class="w-r" v-if="currentContent.type === 1">
          <iframe class="file-show" v-if="fileUrl.length > 0" :src="`${fileUrl}`" frameborder="0"></iframe>
        </div>
        <!--讨论-->
        <div class="d-r" v-if="currentContent.type === 2">
          <div class="discussion">
            <div class="discussion-title">{{ currentContent.sectionDiscussDTO.title }}</div>
            <div class="discussion-content">{{ currentContent.sectionDiscussDTO.content }}</div>
            <div class="my-answer">
              <textarea placeholder="写下你的看法" v-model="currentSectionComment" rows="2" class="post-text"></textarea>
              <div class="primary-btn" @click="saveDiscussComment">提交回答</div>
            </div>
          </div>
        </div>
      </div>
      <div class="interact-section flex-box">
        <div class="left-s left-main">
          <div class="part post-part">
            <div class="part-title">发起提问</div>
            <div class="my-post">
              <div class="post-question">
                <div class="question-content">
                  <textarea
                      class="post-text"
                      placeholder="写下你的问题吧"
                      rows="4"
                  ></textarea>
                </div>
                <ImageGallery
                    :srcs="addedPics"
                    type="shot"
                    @change="handlePicChange"
                    @delete="deletePic"
                ></ImageGallery>
                <div class="submit-btn">提交</div>
              </div>
            </div>
          </div>
          <div class="part question-list-part">
            <div class="part-title">全部提问</div>
            <div class="question-list">
              <div
                  class="question"
                  v-for="question in questions"
                  :key="question.id"
              >
                <div class="description">
                  <span>问题描述：{{ question.content }}</span>
                </div>
                <!--                <ImageGallery-->
                <!--                    :srcs="question.pics.map(a => a.url)"-->
                <!--                    type="show"-->
                <!--                ></ImageGallery>-->
                <div class="answer">
                  <span>回答：{{ question.answer }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="right-side">
          <div class="part menu-part">
            <el-collapse class="chapter-section-main">
              <el-collapse-item class="chapter" v-for="chapter in menu" :key="chapter.id">
                <template slot="title">
                  <span class="chapter-title">{{ chapter.name }}</span>
                </template>
                <div class="chapter-content">
                  <div
                      class="section"
                      v-for="section in chapter.sections"
                      :key="section.id"
                  >
                    <div class="section-title">{{ section.name }}</div>
                    <div class="section-content">
                      <div
                          class="resource"
                          v-for="content in section.contents"
                          :key="content.id"
                          @click="changeLearn(content.id)"
                      >
                        <div class="on" v-if="content.id + '' === currentContent.id + ''">
                          <span class="resource-title">{{ content.name }}</span>
                          <!--                          <span class="status">播放中</span>-->
                        </div>
                        <div v-else>
                          <span class="resource-title">{{ content.name }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
            <!--            <div style="display: none" class="chapter" v-for="chapter in menu" :key="chapter.id">-->
            <!--              <div class="chapter-title">{{ chapter.title }}</div>-->
            <!--              <div class="chapter-content">-->
            <!--                <div-->
            <!--                    class="section"-->
            <!--                    v-for="section in chapter.sections"-->
            <!--                    :key="section.id"-->
            <!--                >-->
            <!--                  <div class="section-title">{{ section.title }}</div>-->
            <!--                  <div class="section-content">-->
            <!--                    <div-->
            <!--                        class="resource"-->
            <!--                        v-for="res in section.resources"-->
            <!--                        :key="res.id"-->
            <!--                        @click="changeLearn(res.id)"-->
            <!--                    >-->
            <!--                      <div class="on" v-if="res.id + '' === resource.id + ''">-->
            <!--                        <span class="resource-title">{{ res.title }}</span>-->
            <!--                        <span class="status">播放中</span>-->
            <!--                      </div>-->
            <!--                      <div v-else>-->
            <!--                        <span class="resource-title">{{ res.title }}</span>-->
            <!--                      </div>-->
            <!--                    </div>-->
            <!--                  </div>-->
            <!--                </div>-->
            <!--              </div>-->
            <!--            </div>-->
          </div>
        </div>
      </div>
    </div>

    <el-dialog class="dialog" title="题目详情" :visible.sync="dialogVisible" :show-close="false">
      <div class="question">
        <div class="content">{{ dialogQuestion.content }}</div>
        <div class="options">
          <div class="option" v-for="(v, k) in dialogQuestion.options" :key="v">
            <input
                type="radio"
                name="dialogQ"
                :id="v + '-' + k"
                :value="k"
                v-model="dialogChosen"
                style="display: none"
            />
            <label :for="v + '-' + k">
                      <span
                          :class="[
                          'chose-icon',
                          dialogQuestion.type === '单选' ? 'circle' : 'squire',
                          {
                            chosen:
                              dialogChosen === k,
                          },
                          {
                            wrong:
                              dialogQuestion.answer !== dialogChosen,
                          },
                        ]"
                      ></span>
              <span class="text">{{ k }}. {{ v }}</span>
            </label>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <div class="primary-btn" @click="confirmDialog">确 定</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ImageGallery from "../../../components/ImageGallery.vue";

export default {
  components: {ImageGallery},
  name: "LearnBenchView",
  data() {
    let originTimeQuestion = {
      // "10": "1",
      // "20": "1"
    };
    let timeQuestion = [];
    for (let k in originTimeQuestion) {
      timeQuestion.push([parseInt(k), originTimeQuestion[k]]);
    }
    timeQuestion.sort((a, b) => {
      return a[0] - b[0];
    });

    return {
      fileUrl: 'http://ckzledu.oss-cn-shanghai.aliyuncs.com/%E4%BA%BA%E7%B1%BB%E5%91%BD%E8%BF%90%E5%85%B1%E5%90%8C%E4%BD%93%E8%A7%86%E5%9F%9F%E4%B8%8B%E7%9A%84%E4%B8%AD%E5%9B%BD%E7%A2%B3%E4%B8%AD%E5%92%8C%E6%96%B9%E6%A1%88.pdf',

      menu: [],

      currentContent: {},
      currentSectionComment: "",

      questions: [],
      addedPics: [],
      dialogVisible: false,
      /*
      *   timeQuestion[i][0] 表示第i个题的时间，[i][1]为题id，需要以时间升序
      * */
      timeQuestion,
      nextQuestionOrder: 0, // 下一个题是第几个（0开始）
      dialogQuestion: {
        id: '10',
        type: '单选',
        content: '你是什么属性',
        options: ['金', '木', '水', '火'],
        answer: 0
      },
      dialogChosen: '',
      myAnswers: [],

      // aliplayer
      options: {
        vid: "",
        playauth: "",
        height: '570px',
        width: '100%',
        disableSeek: false,
        // progressMarkers: [
        //   {offset: 10, text: "除了支持点播和直播的基础播放功能外"},
        //   {offset: 20, text: "深度融合视频云业务"},
        //   {
        //     offset: 30,
        //     text: "为用户提供简单、快速、安全、稳定的视频播放服务",
        //   },
        //   {offset: 40, text: "安装播放器Demo进行体验"},
        //   {offset: 50, text: "开发人员请点击SDK下载"},
        // ],
      },

      updated: false, // 播放是否真正推进，拖回去不会计时
      lastTime: 0, // 新播放起点
      onTime: 0, // 总播放时间

      beforeUnload_time: 0,
      gap_time: 0

    };
  },

  beforeRouteLeave(to, from, next) {
    this.updateProgress();
    console.log('离开路由到新的');
    next(); // 继续路由
  },
  beforeRouteUpdate(to, from, next) {
    this.updateProgress();
    console.log('更新当前路由组件');
    next(); // 继续路由
  },

  destroyed() {
    window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
    window.removeEventListener('unload', e => this.unloadHandler(e))

  },

  mounted() {
    console.log(this.$route.params.contentId);
    this.currentContent.id = this.$route.params.contentId;
    // 加载资源内容
    this.getSectionContentDetail();
    // 加载课程章节
    this.getDetailCourseDirs();
    window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
    window.addEventListener('unload', e => this.unloadHandler(e))

  },



  watch: {
    $route(to) {
      this.currentContent.id = to.params.contentId;
      this.getSectionContentDetail();
    }
  },



  methods: {
    beforeunloadHandler(e){
      this.beforeUnload_time=new Date().getTime();
      /*e = e || window.event;
      if (e) {
        e.returnValue = '关闭后报留当前进度'
      }
      return '关闭后报留当前进度';*/
    },
    unloadHandler(){
      this.gap_time=new Date().getTime()-this.beforeUnload_time;
      //判断是窗口关闭
      if(this.gap_time<=5){
        this.updateProgress();
      }
    },

    seekVideoProgress(last) {
      this.$refs.VueAliplayerV2.seek(last);
    },
    updateProgress() {
      this.handlePause(); //更新之前，处理暂停事件（更新播放时间）
      let type = this.currentContent.type;
      let process = 100;
      if (type === 0) {
        process = Math.min(100, this.currentContent.progress + this.onTime * 100 / this.getDuration())
        process = Math.ceil(process)
      }
      console.log("新进度",process,this.getCurrentTime())
      this.$api.updateProcess({
        sectionContentId:this.currentContent.id,
        process:process,
        lastTime: Math.ceil(this.getCurrentTime())
      }).then(() => {
        console.log(`发送进度更新请求，进度为 ${process}%`);
      });
    },
    getDetailCourseDirs() {
      this.loading = true;
      this.$api.getDetailCourseDirs({
        courseId: this.$route.params.courseId
      }).then((res) => {
        this.menu = res.data.data;
        this.loading = false;
      });
    },
    getSectionContentDetail() {
      this.loading = true;
      this.$api.getSectionContentDetail({
        sectionContentId: this.currentContent.id
      }).then((res) => {
        this.currentContent = res.data.data;
        this.lastTime = this.currentContent.lastTime;
        if (this.currentContent.type === 0) {
          this.options.vid = this.currentContent.resourceDTO.linkId
          this.options.playauth = this.currentContent.resourceDTO.auth
        } else if (this.currentContent.type === 0) {
          this.fileUrl = this.currentContent.resourceDTO.auth
        }
        this.getCourseQuestions()
        this.loading = false;
        this.onTime = 0;
      });
    },
    getCourseQuestions() {
      this.loading = true;
      this.$api.getCourseQuestions({
        pageSize: 20,
        pageNow: 1,
        sectionId:this.currentContent.scId
      }).then((res) => {
        console.log("问题", res.data.rows)
        this.questions = res.data.data.rows;
        this.loading = false;
      });
    },
    saveDiscussComment() {
      this.loading = true
      this.$api.saveDiscussComment({
        discussId: this.currentContent.sectionDiscussDTO.id,
        content: this.currentSectionComment,
      }).then(() => {
        this.loading = false;
      });
    },

    changeLearn(id) {
      this.$router.push({
        name: 'learn-bench',
        params: {
          contentId: id
        }
      })
    },
    // 图片上传相关
    handlePicChange(e) {
      let files = e.target.files;
      for (let file of files) {
        let url = null;
        if (window.createObjectURL != undefined) {
          // basic
          url = window.createObjectURL(file);
        } else if (window.URL != undefined) {
          // mozilla(firefox)
          url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) {
          // webkit or chrome
          url = window.webkitURL.createObjectURL(file);
        }
        this.addedPics.push(url);
      }
    },
    deletePic(i) {
      this.addedPics.splice(i, 1);
    },

    // 弹题相关
    confirmDialog() {
      this.dialogVisible = false;
      this.play();
    },

    // aliplayer
    play() {
      this.$refs.VueAliplayerV2.play();
    },
    pause() {
      this.$refs.VueAliplayerV2.pause();
      this.updateProgress();
    },
    getDuration() {
      return this.$refs.VueAliplayerV2.getDuration();
    },
    replay() {
      this.$refs.VueAliplayerV2.replay();
    },
    getCurrentTime() {
      return this.$refs.VueAliplayerV2.getCurrentTime();
    },

    // 播放器事件回调
    handleReady(e) {
      console.log(`ready`, e);
      this.$nextTick(() => {
        if (this.currentContent) {
          this.seekVideoProgress(this.currentContent.lastTime);
        }
      })
    },
    handlePlay() {
      this.lastTime = this.getCurrentTime();
      console.log('start at ' + this.lastTime);
    },
    handlePause() {
      this.onTime += this.getCurrentTime() - this.lastTime;
      console.log('pause at ' + this.getCurrentTime());
      console.log('lastTime is' + this.lastTime);
      console.log('on time is ' + this.onTime);
    },
    handleCompleteSeek() {
      this.lastTime = this.getCurrentTime();
      console.log('seek to ' + this.lastTime);
    },
    handleTimeupdate() {
      let time = this.getCurrentTime();
      if (this.timeQuestion.length > 0 && Math.abs(time - this.timeQuestion[0][0]) < 0.1) {
        this.pause();
        this.dialogVisible = true;
        // let id = this.timeQuestion[0][1];
        // 请求题目api
        //this.dialogVisible = false;

        this.timeQuestion.shift();
      }
    }
  },

};
</script>

<style scoped lang="scss">
.file-show {
  width: 100%;
  height: 570px;
}

.resource-section {
  height: 570px;
  border-radius: 10px;
  background: #e1e1e1;
}

.d-r .discussion {
  width: 69%;
  display: inline-block;
  margin: 30px 20px;

  > div {
    margin: 20px 0;
  }

  .discussion-title {
    font-size: 20px;
  }

  .my-answer {
    margin-top: 100px;
  }
}

.part {
  margin: 20px 0;
}

.part-title {
  margin-bottom: 20px;
}

.pics {
  margin-bottom: 10px;
}

.pics img {
  margin-right: 10px;
  width: 80px;
  height: 80px;
  border-radius: 10px;

  &.add-pic {
    cursor: pointer;
  }
}

.left-main {
  .my-post {
    position: relative;
    background: #eaeaea;
    padding: 10px;
    border-radius: 10px;
  }

  .question {
    padding: 10px 20px;
    border-radius: 10px;
    background: #eaeaea;
    margin: 10px 0;

    > div {
      margin: 10px 0;
    }
  }
}

.submit-btn {
  position: absolute;
  bottom: 10px;
  right: 10px;
  width: 120px;
  line-height: 35px;
  border-radius: 20px;
  text-align: center;

  color: white;
  font-weight: 600;
  background: #619dff;

  cursor: pointer;
}

.right-side {
  margin-left: 40px;
}

.chapter-section-main {
  border: none;
}

.chapter {
  margin-bottom: 20px;
}

.section {
  margin-bottom: 10px;
}

.chapter-title {
  font-size: 14px;

  overflow:hidden;//隐藏文字
  text-overflow:ellipsis;//显示 ...
  white-space:nowrap;//不换行
  width:270px;
}

.section-title {
  color: #888;
  padding: 10px 20px;
  background: #f6f6f6;
  margin-bottom: 10px;
}

.section-content {
  color: #888;
  font-size: 14px;
}

.resource > div {
  padding: 5px 20px;
  line-height: 2;
}

.chapter-title,
.section-title,
.resource-title {
  cursor: pointer;
  transition: 0.3s;

  &:hover {
    transition: 0.3s;
    color: #357ff8;
  }
}

.on {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
  background: #8eb9ff;
}

.resource .status {
  border-radius: 15px;
  padding: 1px 5px;
  border: 1px solid white;
  font-size: 12px;
  line-height: 1.2;
}

.dialog {
  .question {
    padding: 10px;
  }

  .content {
    margin-bottom: 20px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
}


.option {
  margin: 5px 0;

  label {
    cursor: pointer;
  }

  .chose-icon {
    display: inline-block;
    width: 8px;
    height: 8px;
    border: 3.5px solid #afafaf;
    margin-right: 10px;
    transform: translateY(2px);
    background: #fff;
    transition: 0.2s;
  }

  .chose-icon.chosen {
    transition: 0.2s;
    background: #619dff;
  }

  .chosen.wrong {
    background: #da6d6d;
  }

  .circle {
    border-radius: 50%;
  }
}


</style>
